<template>
  <div class="app-container">
    <div>
      <div >
        <span style="text-align: center;"><h2 >各工序生产日报表</h2></span>
        <div style="text-align: right;">
          <el-button type="primary" :loading="searchLoading" @click="submitDateRworkList">当日报工单提交审核</el-button>
        </div>
      </div>
    </div>
    <el-divider />
        <div>
          <el-form ref="attendanceForm" size="small" :inline="true" label-width="80px">
            <el-form-item label="参与人员:" />
            <el-form-item v-for="(item,index) in attendanceList" :key="index" :label="item.nickName">
              <el-input
                v-model="item.attendanceDay"
                class="def-input-number"
                type="number"
                placeholder="请输入出勤天数(0-2)"
                oninput="if(value){
                 if(Number(value)<0){value=0}} if(Number(value)>2){value=2}"
              />
            </el-form-item>
            <!-- <el-button type="primary" icon="el-icon-upload" size="mini" @click="handleUpdateAttendance">保存</el-button> -->
          </el-form>

        </div>
        <el-divider />
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['sl:rwork:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['sl:rwork:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['sl:rwork:remove']">删除</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" height="550" :data="rworkList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="车间" align="center" prop="slWorkshop.workshopName" />
      <el-table-column label="大工序" align="center" prop="slGprocess.gprocessName" />
      <el-table-column label="小工序" align="center" prop="slProcess.processName" />
      <el-table-column label="生产鼓号" align="center" prop="wtermBatch" >
        <template slot-scope="scope">
          <span>
            {{scope.row.wtermBatch.replace("::",",")}}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="订单编号" align="center" prop="wtermOnumber" />
      <el-table-column label="品种" align="center" prop="breedName" />
      <el-table-column label="操作人" align="center" width="180">
        <template slot-scope="scope">
          <span v-for="(item,index) in scope.row.slRworkRmemberList" :key="index">
            {{item.rmemberNick}} {{index === scope.row.slRworkRmemberList.length-1 ? "":","}}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="颜色" align="center" prop="colourName" />
      <el-table-column label="工艺要求" align="center" prop="rworkTr" />
      <el-table-column label="单位" align="center" prop="rworkDw" />
      <el-table-column label="计划生产" align="center" prop="rworkPlan" />
      <el-table-column label="总生产" align="center" prop="rworkActual" />
      <el-table-column label="工序单价" align="center" prop="processPay" />
      <el-table-column label="开始时间" align="center" prop="rworkStart" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.rworkStart, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="rworkEnd" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.rworkEnd, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工作时长" align="center" prop="rworkDuration" />

      <el-table-column label="预估工资" align="center" prop="estimatePay" />
      <el-table-column fixed="right" label="操作" width="250" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" @click="recordTime(scope.row,'start')" v-hasPermi="['sl:rwork:edit']" circle
            :disabled="scope.row.rworkStart?true:false">开始</el-button>
          <el-button type="danger" @click="recordTime(scope.row,'end')" v-hasPermi="['sl:rwork:edit']" circle
            :disabled="scope.row.rworkEnd?true:false">结束</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['sl:rwork:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['sl:rwork:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改报工单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row v-if="form.wtermInfo!=null" v-for="(wterm, index) in form.wtermInfo" :key="index">
          <el-col :span="10">
            <el-form-item
                :label="'生产鼓号/生产批号'"
                label-width="140px"
                :key="wterm.key"
                :prop="'wtermInfo.' + index + '.wtermNum'"
              >
              <el-input v-model="wterm.wtermNum"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
                :label="'实际生产'"
                label-width="120px"
                :key="wterm.key"
                :prop="'wtermInfo.' + index + '.quantum'"
                :rules="rules.quantum"
              >
              <el-input v-model="wterm.quantum" class="def-input-number" type="number"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-button type="primary" icon="el-icon-plus"  @click="addWtermn" circle></el-button>
            <el-button type="danger" icon="el-icon-delete" v-if="form.wtermInfo.length>1" @click.prevent="removeWtermn(wterm)" circle></el-button>
          </el-col>
        </el-row>

        <el-row>
   <!--       <el-col :span="12">
            <el-form-item label="生产鼓号/生产批号" label-width="140px" prop="wtermDnumber">
              <el-input v-model="form.wtermDnumber" placeholder="请输入生产鼓号" />
            </el-form-item>
          </el-col> -->
         <el-col :span="12">
           <el-form-item label="订单编号"  prop="wtermOnumber">
             <el-autocomplete class="inline-input" v-model="form.wtermOnumber" :fetch-suggestions="querySearchOrder"
               placeholder="请输入订单编号" :trigger-on-focus="false"></el-autocomplete>
           </el-form-item>
         </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="所属模块" prop="moduleId">
              <el-select v-model="form.moduleId" :disabled="true" filterable @change="handleChangeModule" placeholder="请选择所属模块">
                <el-option v-for="item in moduleOptions" :key="item.moduleId" :label="item.moduleName"
                  :value="item.moduleId" :disabled="item.status == 1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属车间" prop="workshopId">
              <el-select v-model="form.workshopId" filterable @change="handleChangeWorkshop" placeholder="请选择所属车间">
                <el-option v-for="item in workshopOptions" :key="item.workshopId" :label="item.workshopName"
                  :value="item.workshopId" :disabled="item.status == 1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="大工序" prop="gprocessId">
              <el-select v-model="form.gprocessId" filterable @change="handleChangeProcess" placeholder="请选择大工序">
                <el-option v-for="item in gprocessOptions" :key="item.gprocessId" :label="item.gprocessName"
                  :value="item.gprocessId" :disabled="item.status == 1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="小工序" prop="processId">
              <el-select v-model="form.processId" filterable @change="handleGetProcessPay" placeholder="请选择小工序">
                <el-option v-for="item in processOptions" :key="item.processId" :label="item.processName"
                  :value="item.processId" :disabled="item.status == 1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工序单价" prop="processPay">
              <el-input v-model="form.processPay" :disabled="true" placeholder="选择小工序后自动获取" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="品种" prop="breedId">
               <el-autocomplete class="inline-input" v-model="form.breedName" :fetch-suggestions="querySearchBreed"
                placeholder="请输入品种" :trigger-on-focus="false"></el-autocomplete>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="颜色" prop="colourId">
             <el-autocomplete class="inline-input" v-model="form.colourName" :fetch-suggestions="querySearchColour"
                placeholder="请输入颜色" :trigger-on-focus="false"></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工艺要求" prop="rworkTr">
              <el-input v-model="form.rworkTr" placeholder="请输入工艺要求" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位" prop="rworkDw">
              <el-input v-model="form.rworkDw" placeholder="请输入单位" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="计划生产" prop="rworkPlan">
              <el-input v-model="form.rworkPlan" class="def-input-number" type="number" placeholder="请输入计划生产" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总生产" prop="rworkActual">
              <el-input v-model="form.rworkActual" :disabled="true" class="def-input-number" type="number"
                placeholder="请输入总生产" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="重复次数" prop="rworkRepetitions">
              <el-input-number v-model="form.rworkRepetitions" controls-position="right" :min="1" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="开始时间" prop="rworkStart">
              <el-date-picker clearable style="width:100%" v-model="form.rworkStart" type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss" default-time="12:00:00" placeholder="请选择开始时间"
                :picker-options="pickerOptions" @change="handleCompareTime">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结束时间" prop="rworkEnd">
              <el-date-picker clearable style="width:100%" v-model="form.rworkEnd" type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss" default-time="12:00:00" placeholder="请选择结束时间"
                :picker-options="pickerOptions" @change="handleCompareTime">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工作时长" prop="rworkDuration">
              <el-input v-model="form.rworkDuration"  class="def-input-number" type="number" placeholder="请输入工作时长" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="预估工资" prop="estimatePay">
              <el-input v-model="form.estimatePay" :disabled="true" placeholder="请输入预估工资" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="center">操作人</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddSlRworkRmember">添加</el-button>
          </el-col>
          <UserMultiSelect ref="userSelect" @onSelected="userSelected"></UserMultiSelect>
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-user" size="mini" @click="handleGetLastRmember">上一次操作人</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-brush" size="mini" @click="handleClearRmember">清除操作人</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini"
              @click="handleDeleteSlRworkRmember">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="slRworkRmemberList" :row-class-name="rowSlRworkRmemberIndex"
          @selection-change="handleSlRworkRmemberSelectionChange" ref="slRworkRmember" style="width:100%">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50" />
          <el-table-column label="参与人" align="center" prop="rmemberNick" width="80"/>
          <el-table-column label="职级" prop="levelName" />
          <el-table-column label="计薪方式" prop="ssmName" />
          <el-table-column label="时长" align="center" >
            <template slot-scope="scope" v-if="scope.row.ssmId=='5'||scope.row.levelId=='7'||scope.row.levelId=='8'||scope.row.levelId=='9'">
                <el-input required v-model="scope.row.rmemberDuration" class="def-input-number" type="number" placeholder="请输入时长" />
            </template>
          </el-table-column>
          <el-table-column label="班组" prop="rmemberBz" >
            <template slot-scope="scope">
              <el-select v-model="scope.row.rmemberBz" placeholder="请选择班组" clearable>
                <el-option
                  v-for="dict in dict.type.sl_rwork_class"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {getLastmember,listNoSubmitRwork,listRwork,getRwork,delRwork,addRwork,updateRwork,updateRworkDateTime,rworkUserBase,getRworkOptions,isUniqueUser,submitDateRworks} from "@/api/sl/rwork";
  import {getProcessListByGprocessId,getProcessPay} from "@/api/sl/process";
  import UserMultiSelect from "@/components/userSelect/multi.vue"
  import {formatDate,formatOnlyDate} from '@/utils/index'
  import {allAttendance,addAttendance,updateAttendance, updateAttendanceList} from "@/api/sl/attendance";
  import {getAllOrder} from "@/api/sl/order";
  import {getAllColour} from "@/api/sl/colour";
  import {getAllBreed} from "@/api/sl/breed";
  import {getWorkshopListByModuleId} from "@/api/sl/workshop";
  import {getGprocessListByWorkshopId} from "@/api/sl/gprocess";
  import {allRworkMember,allRworkMemberByRworkId} from "@/api/sl/rmember.js";


  export default {
    name: "Rwork",
    components: {UserMultiSelect},
    dicts: ['sl_rwork_class','sys_yes_no'],
    data() {
      let watermarkContentVaild=(rule, value, callback)=>{
        if(value==null || value===""){
          callback();
        }else{
          let length=value.length
          if(length>7){
            callback(new Error("输入不能超过7位"))
          }else{
            callback();
          }
        }
      }
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 报工单表格数据
        rworkList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        searchLoading: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 999,
          rworkDate: null,
          moduleId: null,
          workshopId: null,
          rworkBz: null,
          rworkYear: null,
          rworkMonth: null,
          rworkDay: null,
          isApproved: null,
          leaderUser: null,
          wtermDnumber: null,
          wtermOnumber: null,
          gprocessId: null,
          processId: null,
          rworkStart: null,
          rworkEnd: null,
        },
        // 表单参数
        form: {
          //批量鼓号和数量
          wtermInfo: [{
            wtermNum: '',
            quantum : 0
          }],
        },
        // 表单校验
        rules: {
          moduleId: [
            {required: true,message: "模块不能为空",trigger: "blur"},
          ],
          workshopId: [
            {required: true,message: "车间不能为空",trigger: "blur"},
          ],
          gprocessId: [
            {required: true,message: "大工序ID不能为空",trigger: "blur"},
          ],
          processId: [
            {required: true,message: "小工序ID不能为空",trigger: "blur"},
          ],
          processPay: [
            {required: true,message: "工序单价不能为空",trigger: "blur"}
          ],
          rworkPlan: [
            {validator: watermarkContentVaild, trigger: 'blur'}
          ],
          rworkActual: [
            {validator: watermarkContentVaild, trigger: 'blur'}
          ],
          rworkDuration: [
            {validator: watermarkContentVaild, trigger: 'blur'}
          ],
          estimatePay: [
            {validator: watermarkContentVaild, trigger: 'blur'}
          ],
          quantum: [
             {validator: watermarkContentVaild, trigger: 'blur'}
          ],
        },
        rworkUser: null,
        //早晚班
        rworkClass: null,
        //模块
        moduleOptions: [],
        //车间
        workshopOptions: [],
        //大工序
        gprocessOptions: [],
        //小工序
        processOptions: [],
        // 操作人表格数据
        slRworkRmemberList: [],
        //限制时间选择范围
        pickerOptions: {
          disabledDate(date) {
            let ts = date.getTime()
            let now = Date.now()
            let limitDays = 2 * 24 * 60 * 60 * 1000 // 2天的毫秒数
            if (ts <= now && ts >= now - limitDays) {
              return false;
            } else {
              return true;
            }
          }
        },
        //所有参与人
        attendanceList: [],
        //订单编号
        orderNumList: [],
        //颜色
        colourList: [],
        //品类
        breedList: [],
      };
    },
    created() {
      //获取当前报工人信息
      this.getRworkUserBase(this.$store.state.user.name);

      this.getList();
    },
    watch: {
      "form.processPay":{
        handler(newName, oldName) {
          this.handleCountPay()
        },
      },
      "form.rworkActual":{
        handler(newName, oldName) {
          this.handleCountPay()
        },
      },
      "form.rworkRepetitions":{
        handler(newName, oldName) {
          this.handleCountPay()
        },
      },
      "form.wtermInfo":{
        handler(newName, oldName) {
          this.countAllquantum(newName)
        },
        deep : true
      }
    },
    methods: {
      /** 查询报工单列表 */
      getList() {
        this.loading = true;
        listNoSubmitRwork(this.queryParams).then(response => {
          this.rworkList = response.rows;
          this.total = response.total;
          this.loading = false;
          //处理出勤人
          this.getAllRworkMember();
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          rworkId: null,
          rworkDate: null,
          moduleId: null,
          workshopId: null,
          rworkBz: null,
          rworkYear: null,
          rworkMonth: null,
          rworkDay: null,
          isApproved: null,
          createBy: null,
          createTime: null,
          leaderUser: null,
          wtermDnumber: null,
          wtermOnumber: null,
          gprocessId: null,
          processId: null,
          breedName: null,
          colourName: null,
          rworkTr: null,
          rworkDw: null,
          rworkPlan: null,
          rworkActual: null,
          rworkRepetitions: 1,
          rworkStart: null,
          rworkEnd: null,
          rworkDuration: null,
          processPay: null,
          estimatePay: null,
          rworkUser: null,
          rworkDm: null,
          rfworkId: null,
          wtermBatch: null,
          actualBatch: null,
          isBatch : 'Y',
          //批量鼓号和数量
          wtermInfo: [{
              wtermNum: '',
              quantum : 0
          }],

        };
        this.slRworkRmemberList = [];
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.rworkId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        var obj = {};
        obj.moduleId = this.rworkUser.moduleId;
        obj.workshopId = this.rworkUser.workshopId;
        obj.leaderUser = this.rworkUser.leaderUser;
        getRworkOptions(obj).then(response => {
          //最后一次报工数据
          if(null!= response.data){
            this.form = response.data;

            //初始化批量报工
            this.form.wtermInfo = [{
                wtermNum: '',
                quantum : 0
            }]

          }else{
            this.form.moduleId = this.rworkUser.moduleId;
            this.form.workshopId = this.rworkUser.workshopId;
            this.form.leaderUser = this.rworkUser.leaderUser;
          }
          this.moduleOptions = response.modules;
          this.workshopOptions = response.workshops,
          this.gprocessOptions = response.gprocesss,
          this.processOptions = response.processs,
          this.open = true;
          this.title = "添加报工项";
        });
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const rworkId = row.rworkId || this.ids
        getRwork(rworkId).then(response => {
          this.form = response.data;
          this.gprocessOptions = response.gprocesss;
          this.processOptions = response.processs;
          this.moduleOptions = response.modules;
          this.workshopOptions = response.workshops;
          this.slRworkRmemberList = response.data.slRworkRmemberList;
          this.open = true;
          this.title = "修改报工单";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.slRworkRmemberList.length == 0) {
              this.$modal.msgError("操作人不能为空。");
              return;
            }
            this.form.slRworkRmemberList = this.slRworkRmemberList;
            if (this.form.rworkId != null) {
              updateRwork(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addRwork(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const rworkIds = row.rworkId || this.ids;
        this.$modal.confirm('是否确认删除报工单编号为"' + rworkIds + '"的数据项？').then(function() {
          return delRwork(rworkIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('sl/rwork/export', {
          ...this.queryParams
        }, `rwork_${new Date().getTime()}.xlsx`)
      },
      //获取报工人模块车间信息
      getRworkUserBase(userName){
        if(userName!=null && userName!=""){
          rworkUserBase(userName).then(response => {
            if(response.data!=null){
              this.rworkUser = response.data;
              if(null == this.rworkUser.leaderUser){
                this.$modal.msgError("未获取到您的直属领导，请联系管理员。");
              }
            }else{
              this.$modal.msgError("未获取到您的直属领导，请联系管理员。");
            }
          });
        }
      },
      //获取所有出勤人
      getAllRworkMember() {
        allRworkMember(this.queryParams).then(response => {
          this.attendanceList = response.data.map(item => ({
            "userName": item.rmemberUser,
            "nickName": item.rmemberNick,
            "attendanceDay":1
          }))
        });
      },
      //模块变更查询车间
      handleChangeModule(value) {
        //清空车间
        this.form.workshopId = null;
        this.workshopOptions = [];
        //清空大工序
        this.form.gprocessId = null;
        this.gprocessOptions = [];
        //清空小工序
        this.form.processId = null;
        this.processOptions = [];
        //工序单价
        this.form.processPay = null;
        getWorkshopListByModuleId(value).then(response => {
          this.workshopOptions = response.data;
        });
      },
      //车间变更查询大工序
      handleChangeWorkshop(value) {
        //清空大工序
        this.form.gprocessId = null;
        this.gprocessOptions = [];
        //清空小工序
        this.form.processId = null;
        this.processOptions = [];
        //工序单价
        this.form.processPay = null;
        getGprocessListByWorkshopId(value).then(response => {
          this.gprocessOptions = response.data;
        });
      },
      //大工序变更查询小工序
      handleChangeProcess(value) {
        //清空小工序
        this.form.processId = null;
        this.processOptions = [];
        //工序单价
        this.form.processPay = null;
        getProcessListByGprocessId(value).then(response => {
          this.processOptions = response.data;
        });
      },
      //获取小工序单价
      handleGetProcessPay(value) {
        for (let i = 0; i < this.processOptions.length; i++) {
          if (this.processOptions[i].processId === value) {
            this.form.processPay = this.processOptions[i].processPay;
            break;
          }
        }
      },
      //比较时间
      handleCompareTime() {
        if (this.form.rworkStart && this.form.rworkEnd) {
          let difference = new Date(this.form.rworkEnd) - new Date(this.form.rworkStart);
          this.form.rworkDuration = (difference / 3600000).toFixed(2)
        } else {
          this.form.rworkDuration = null;
        }
      },
      /** 操作人序号 */
      rowSlRworkRmemberIndex({row,rowIndex}) {
        row.index = rowIndex + 1;
      },
      /** 操作人添加按钮操作 */
      handleAddSlRworkRmember() {
        this.$refs.userSelect.showFlag = true;
      },
      /** 操作人删除按钮操作 */
      handleDeleteSlRworkRmember() {
        if (this.checkedSlRworkRmember.length == 0) {
          this.$modal.msgError("请先选择要删除的操作人数据");
        } else {
          const slRworkRmemberList = this.slRworkRmemberList;
          const checkedSlRworkRmember = this.checkedSlRworkRmember;
          this.slRworkRmemberList = slRworkRmemberList.filter(function(item) {
            return checkedSlRworkRmember.indexOf(item.index) == -1
          });
        }
      },
      /** 复选框选中数据 */
      handleSlRworkRmemberSelectionChange(selection) {
        this.checkedSlRworkRmember = selection.map(item => item.index)
      },
      userSelected(rows) {
        if (rows != null) {
          rows.forEach(user => {
            let obj = {};
            obj.rmemberUser = user.userName;
            obj.rmemberNick = user.nickName;
            obj.levelId = user.levelId;
            obj.ssmId = user.ssmId;
            obj.levelName = user.level.levelName;
            obj.ssmName = user.ssm.ssmName;
            obj.isFormalworker = user.isFormalworker;
            obj.isHourlyworker = user.isHourlyworker;
            obj.rmemberBz = '3';
            if (isUniqueUser(this.slRworkRmemberList, obj)) {
              this.slRworkRmemberList.push(obj);
            }
          })
        }
      },
      handleCountPay() {
        this.form.estimatePay = Math.floor(this.form.processPay * this.form.rworkActual * this.form.rworkRepetitions * 1000) / 1000;
      },
      /** 记录开始结束时间 */
      recordTime(row, type) {
        const rworkId = row.rworkId || this.ids
        let tmpData;
        let nowDate = formatDate(new Date());
        if (type === "start") {
          tmpData = {
            "rworkId": rworkId,
            "rworkStart": nowDate
          }
        } else if (type === "end") {
          tmpData = {
            "rworkId": rworkId,
            "rworkEnd": nowDate
          }
        }
        updateRworkDateTime(tmpData).then(response => {
          this.$modal.msgSuccess("记录成功");
          this.getList();
        });
      },
      querySearchOrder(queryString, cb) {
        var orderNumList = this.orderNumList;
        var results = queryString ? orderNumList.filter(this.createFilter(queryString,"order")) : orderNumList;
        cb(results);
      },
      querySearchBreed(queryString, cb) {
        var breedList = this.breedList;
        var results = queryString ? breedList.filter(this.createFilter(queryString,"breed")) : breedList;
        cb(results);
      },
      querySearchColour(queryString, cb) {
        var colourList = this.colourList;
        var results = queryString ? colourList.filter(this.createFilter(queryString,"colour")) : colourList;
        cb(results);
      },
      createFilter(queryString,type) {
        if(type==="order"){
          return (order) => {
            return (order.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
          };
        }else if(type==="colour"){
          return (colour) => {
            return (colour.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
          };
        }else if(type==="breed"){
          return (breed) => {
            return (breed.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
          };
        }
      },
      //当日报工单提交
      submitDateRworkList(){
        let valid = true;
        if(this.rworkList.length==0){
          return;
        }
        //校验所有实际生产不能为空
        for(let i=0;i<this.rworkList.length;i++){
          if(this.rworkList[i].actualBatch!=null){
            let arrActualBatch = this.rworkList[i].actualBatch.split("::");
            for(let n=0;n<arrActualBatch.length;n++){
              if(arrActualBatch[n].trim() ===""){
                this.$modal.msgError("请检查第"+(i+1)+"条的实际生产");
                valid = false;
                break;
              }
            }
          }else{
            this.$modal.msgError("请检查第"+(i+1)+"条的实际生产");
            valid = false;
            break;
          }
        }
        //校验所有人工勤不能为空
        for(let i=0;i<this.attendanceList.length;i++){
          if(this.attendanceList[i].attendanceDay==null || this.attendanceList[i].attendanceDay==""){
              this.$modal.msgError("参与人员"+this.attendanceList[i].nickName+"的出勤天数不能为空。");
              valid = false;
              break;
          }
        }
        //校验所有小时工操作人的时长是否填写
        for(let i=0;i<this.rworkList.length;i++){
          allRworkMemberByRworkId(this.rworkList[i].rworkId).then(response => {
            let tmpMemberList = response.data;
            for(let n=0;n<tmpMemberList.length;n++){
              if(tmpMemberList[n].ssmId===5||tmpMemberList[n].levelId=='7'||tmpMemberList[n].levelId=='8'||tmpMemberList[n].levelId=='9'){
                if(tmpMemberList[n].rmemberDuration==null||tmpMemberList[n].rmemberDuration===""){
                  this.$modal.msgError("第"+(i+1)+"条报工项的操作人"+tmpMemberList[n].rmemberNick+"出勤时长不能为空。");
                  valid = false;
                  break;
                }
              }
            }
          });
        }
        //提交整张报工单
        if(valid){
          let tmpData = {};
          tmpData.rworks = this.rworkList;
          tmpData.attendances = this.attendanceList;
          this.searchLoading = true;
          submitDateRworks(tmpData).then(response => {
            this.$modal.msgSuccess("提交成功");
            this.getList();
            this.searchLoading = false;
          });
        }
      },
      removeWtermn(item) {
        var index = this.form.wtermInfo.indexOf(item)
        if (index !== -1) {
          this.form.wtermInfo.splice(index, 1)
        }
      },
      addWtermn() {
        this.form.wtermInfo.push({
          wtermNum: '',
          quantum: 0,
          key: Date.now()
        });
      },
      //所有实际产量
      countAllquantum(arr){
        let num = 0;
        arr.forEach(wterm => {
          num = num + Number(wterm.quantum);
        })
        this.form.rworkActual = Math.round(num * 1000) / 1000;
      },
      //获取最后一次操作人
      handleGetLastRmember(){
        getLastmember().then(response=>{
          console.log(response.data)
          if(null!=response.data){
            this.slRworkRmemberList = response.data
          }else{
            this.$modal.msgError("未获取到上一次操作人。");
          }

        })
      },
      //清空操作人
      handleClearRmember(){
          this.slRworkRmemberList = [];
      }
    },
    //挂载订单号
    mounted() {
      getAllOrder().then(response => {
        this.orderNumList = response.data.map(item => ({
          "value": item.orderNum,
        }))
      });
      getAllColour().then(response => {
        this.colourList = response.data.map(item => ({
          "value": item.colourName,
        }))
      });
      getAllBreed().then(response => {
        this.breedList = response.data.map(item => ({
          "value": item.breedName,
        }))
      });
    },
  }
</script>
<style>
.el-table .el-table__body-wrapper::-webkit-scrollbar {
    height: 10px;
}
</style>
